

/*
本插件为配合Kugar.AdminLTE控件框架使用的表格功能,主要提供了左右两侧固定列,排序按钮功能
用于取代jqTable,由于jqTable过于复杂,列宽等不容配置,因此单独编写了这个控件,用于实现部分常用的表格功能

调用的方式:
      $("#testtb").simpleTable({
        leftFloatCol: parseInt($("#testtb").data("leftfloat")),    //左侧浮动n列,默认为0
        rightFloatCol: parseInt($("#testtb").data("rightfloat")),  //右侧浮动n列,,默认为0
        scrollY:false,                                             //是否使用高度固定的滚动条功能
        scrollHeight:0,                                            //固定的高度,单位为px,默认为0,只能是数字
      }).on("webui_table.sort",function(e,data){  
        //点击刷新按钮触发的事件data为事件内容  data.sortType 为修改后的排序方式: asc,desc,unsort 三种   data.sortKey 为排序列的key
        //请注意在这个时间中,自行增加loading防止多次出发
        var p=0;
      })
      .on("webui_table.refresh",function(e){
        //出发刷新功能的时候,触发该事件,

      }).on("webui_table.init",function(e){
          //控件初始化完成后,触发该事件
      })
      ;

      $("#testtb").simpleTable().refresh();   //该函数用于刷新表格,重新应用表格样式
      $("#testtb").simpleTable().cleanWrap();   //该函数用于清空表格样式,还原原来的表格

*/

; (function ($) {
    $.fn.simpleTable = function (options) {
        var defaults = {
            //各种参数、各种属性
            leftFloatCol: 0,
            rightFloatCol: 0,
            scrollY: false,
            scrollHeight: 200
        };

        var isInitCompleted = false;

        //options合并到defaults上,defaults继承了options上的各种属性和方法,将所有的赋值给endOptions
        var endOptions = $.extend(defaults, options);

        var $table = $($(this).first());

        if (!$table.is("table.webui_table")) {
            return null;
        }

        var obj = $table.data("webui_table_object");

        if (obj) {
            return obj;
        }

        //处理内容Y轴滚动事件
        var __onScrollYHandler = function (event) {
            var st = $(this).scrollTop();

            var tmpLeft = $(this).data("leftFloatDiv");

            if (tmpLeft) {
                tmpLeft.scrollTop(st);
            }

            var tmpRight = $(this).data("rightFloatDiv");

            if (tmpRight) {
                tmpRight.scrollTop(st);
            }
        };

        var __onSortByButtonClick = function (event) {
            //排序按钮变化的顺序为: 未排序-升序--降序-未排序
            var $this = $(this);

            var newSortType = "";

            if ($this.is(".fa-sort")) { // 未排序
                $this.removeClass("fa-sort").addClass("fa-sort-amount-asc");
                newSortType = "asc";
            }
            else if ($this.is(".fa-sort-amount-asc")) {
                $this.removeClass("fa-sort-amount-asc").addClass("fa-sort-amount-desc");
                newSortType = "desc";
            }
            else if ($this.is(".fa-sort-amount-desc")) {
                $this.removeClass("fa-sort-amount-desc").addClass("fa-sort");
                newSortType = "unsort";
            }

            event.stopPropagation();

            $table.trigger("webui_table.sort",
                {
                    sortType: newSortType,
                    sortKey: $this.data("sortkey"),
                    triggerElement: this,
                });
        };

        //去除table的包装元素
        this.cleanWrap = function () {
            if (!$table.is('.wraped')) {
                return this;
            }

            var wrapper = $table.closest(".webui_table_wrapper");

            $table.insertBefore(wrapper);

            wrapper.remove();

            if (isInitCompleted) {
                $table.trigger("webui_table.cleanwrapper", this);
            }

        }

        //重新组装table
        this.refresh = function () {
            this.cleanWrap();

            var realTable = $table;

            realTable.find("td .table_column_buttonlist").each(function() {
                var w = $(this).outerWidth();
                $(this).closest("td").width(w);
            });

            var realTableParent = $(realTable).parent();

            var outSideBox = $(
                "<div class=\"box no-border no-margin webui_table_wrapper hidden\"><div class=\"box-body no-padding\"></div></div>"
            );
            var outSideBoxBody = $(outSideBox).children(".box-body");

            var leftFloatQty = endOptions.leftFloatCol;
            var rightFloatQty = endOptions.rightFloatCol;

            var leftFloatDiv, rightFloatDiv;
            var leftFloatTable, rightFloatTable;

            var leftFloatTableWidth = 0,
                rightFloatTableWidth = 0;

            var headerMaxHeight = 0;

            $(realTable).find("thead th").each(function() {
                if ($(this).outerHeight() > headerMaxHeight) {
                    headerMaxHeight = $(this).outerHeight();
                }
            });

            //开始计算左侧浮动列
            if (leftFloatQty > 0) {
                leftFloatDiv = $("<div class=\"webui_table_float_left hidden\"><table></table></div>");
                leftFloatTable = $(leftFloatDiv).children("table");
                leftFloatTable.attr("class", realTable.attr("class"));
                leftFloatTable.removeClass("webui_table");

                leftFloatTable.append($(realTable).children("thead").clone(true, true));
           
                leftFloatTable.find("thead th").each(function (index, e) {
                    if (index > leftFloatQty - 1) {
                        $(e).remove();
                    } else {
                        leftFloatTableWidth += $(realTable).children("thead").find("tr:eq(0) th:eq(" + index + ")")
                            .outerWidth();
                        $(this).height(headerMaxHeight);
                    }
                });

                leftFloatTable.append("<tbody></tbody>");

                outSideBoxBody.append(leftFloatDiv);

                $(leftFloatTable).height($(realTable).outerHeight());
                $(leftFloatTable).children("thead").height($(realTable).children("thead").height());
            }

            //开始计算右侧浮动列
            if (rightFloatQty > 0) {
                rightFloatDiv = $("<div class=\"webui_table_float_right hidden\"><table></table></div>");
                rightFloatTable = $(rightFloatDiv).children("table");
                rightFloatTable.attr("class", realTable.attr("class"));
                rightFloatTable.removeClass("webui_table");


                rightFloatTable.append($(realTable).find("thead").clone(true,true)); //复制整个表头

                var thCount = rightFloatTable.find("th").length - rightFloatQty;
                rightFloatTable.find("thead th").each(function (index, e) {
                    if (index < thCount) { //删除非浮动列的表头
                        $(e).remove();
                    } else {
                        rightFloatTableWidth += $(realTable).children("thead").find("tr:eq(0) th:eq(" + index + ")")
                            .outerWidth();
                        $(this).height(headerMaxHeight);
                    }
                });

                rightFloatTable.append("<tbody></tbody>");

                outSideBoxBody.append(rightFloatDiv);

                $(rightFloatTable).height($(realTable).outerHeight());
                $(rightFloatTable).children("thead").height($(realTable).children("thead").height());
            }

            var realTableRows = $(realTable).children("tbody").children("tr");
            //开始复制数据行
            realTableRows.each(function (index, e) {
                var row = $(e);
                var tdlst = $(row).children("td");
                var sourceHeight = $(e).height();

                if (leftFloatTable) {
                    var r = $("<tr></tr>");

                    for (var i = 0; i < leftFloatQty; i++) {
                        r.append($(tdlst[i]).clone(true,true));
                        
                    }
                    r.height(sourceHeight + "px");
                    leftFloatTable.append(r);
                }

                if (rightFloatTable) {
                    var r = $("<tr></tr>");

                    for (var i = rightFloatQty - 1; i >= 0; i--) {
                        r.append($(tdlst[tdlst.length - 1 - i]).clone(true, true));
                    }

                    r.height(sourceHeight + "px");
                    rightFloatTable.append(r);
                }
            });

            $(outSideBoxBody).append("<div class=\"webui_table_float_tablecontent\"></div>");

            outSideBox.insertBefore(realTable);

            $(outSideBoxBody).children(".webui_table_float_tablecontent").append(realTable);

            if (outSideBox) {
                outSideBox.removeClass("hidden");
            }

            if (leftFloatDiv) {
                leftFloatDiv.removeClass("hidden");

                if (leftFloatTableWidth > outSideBoxBody.width()) {
                    leftFloatTableWidth = outSideBoxBody.width();
                }

                $(leftFloatTable).width(leftFloatTableWidth);
            }

            if (rightFloatDiv) {
                rightFloatDiv.removeClass("hidden");

                if (rightFloatTableWidth > outSideBoxBody.width()) {
                    rightFloatTableWidth = outSideBoxBody.width();
                }

                $(rightFloatTable).width(rightFloatTableWidth);
            }

            realTable.addClass("wraped");

            if (endOptions.scrollY && endOptions.scrollHeight > 0) {
                var scrollWidth = getScrollWidth();
                var content = $(outSideBoxBody).children(".webui_table_float_tablecontent");

                content.css("overflow-y", "auto").css("max-height", endOptions.scrollHeight + "px");

                var floatDivMaxHeight = content[0].scrollWidth > content[0].clientWidth ? (endOptions.scrollHeight - scrollWidth) : endOptions.scrollHeight;

                if (leftFloatDiv) {
                    leftFloatDiv
                        .css("max-height", floatDivMaxHeight + "px")
                        .css("overflow", "hidden");

                    content.data("leftFloatDiv", leftFloatDiv);
                }

                if (rightFloatDiv) {
                    rightFloatDiv
                        .css("max-height", floatDivMaxHeight + "px")
                        .css("right", content[0].scrollHeight > content[0].clientHeight ? scrollWidth : 0)
                        .css("overflow", "hidden");

                    content.data("rightFloatDiv", rightFloatDiv);
                }

                content.scroll(__onScrollYHandler);
            }
            
            outSideBoxBody.find("td .delrow").each(function () {
                $(this).click(function () {
                    var that = $(this);
                    WebUIJS.Confirm("是否删除该行?","删除确认", function () {
                            $(that).closest("tr").remove();
                            //.remove();
                            $table.simpleTable().refresh();
                        }
                    );
                });
            });

            var onSortClick = debounce(200, __onSortByButtonClick);
            outSideBox.find("i.head-sort-icon").click(onSortClick);

            $(realTable).find("th").each(function (index, item) {
                if ($(item).hasClass("selectcol")) {
                    $(item).find(":checkbox").change(function () {
                        var isChecked = $(this).is(":checked");
                        $(realTable).find("tbody tr").each(function () {
                            var checkbox = $($(this).find("td")[index]).find(".layui-form-checkbox");
                            if (isChecked !== checkbox.is(".layui-form-checked")) {
                                checkbox.click();
                            }
                        });
                    });
                }
            });

            if (isInitCompleted) {
                realTable.trigger("webui_table.refresh", this);
            }

        }


        this.refresh();
        isInitCompleted = true;

        $table.data("webui_table_object", this);
        $table.trigger("webui_table.init", this);

        return this;
    };

    var debounce = function (idle, action) {
        var last
        return function () {
            var ctx = this, args = arguments
            clearTimeout(last)
            last = setTimeout(function () {
                action.apply(ctx, args)
            }, idle)
        }
    }
})(jQuery);

function getScrollWidth() {
    var noScroll, scroll, oDiv = document.createElement("DIV");
    oDiv.style.cssText = "position:absolute; top:-1000px; width:100px; height:100px; overflow:hidden;";
    noScroll = document.body.appendChild(oDiv).clientWidth;
    oDiv.style.overflowY = "scroll";
    scroll = oDiv.clientWidth;
    document.body.removeChild(oDiv);
    return noScroll - scroll;
}